import {Component, EventEmitter, OnInit, Output, ViewChild, AfterViewInit } from '@angular/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { ApiService } from '@core/services/http/api.service';
import { UserAuthService } from '@core/services/user-auth.service';
import { Router } from '@angular/router';
import {ApesMessageService} from "@shared/apes/message";
import {DatePipe} from "@angular/common";
import {CarDetailsComponent} from "./car-details/car-details.component";

@Component({
  selector: 'car-info',
  templateUrl: './car-info.component.html',
  styleUrls: ['./car-info.component.scss']
})
export class CarInfoComponent implements OnInit, AfterViewInit {
  @ViewChild(CarDetailsComponent,{static:false}) child: CarDetailsComponent;
  @Output() loadStates = new EventEmitter<any>();

  rowData: any[] = [];
  posts: any;
  gridStyle = {
    padding: 0
  };
  visible = false;
  width = document.body.scrollWidth;
  height = window.screen.availHeight;
  isRefresh: boolean;
  val: string = '更多';
  try: number = -1;
  detailsData: any;
  queryList: any[];
  query: string = 'CarInStore';

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private userAuthService: UserAuthService,
              private router: Router, private datePipe: DatePipe,
              private msg: ApesMessageService) {
    const userInfo = this.userAuthService.getUserInfoObj();
    if(userInfo.userAccount.post.branchObj !== undefined) {
      this.posts = userInfo.userAccount.post.branchObj.origin;
    // if(userInfo.userAccount.post.dept !== undefined) {
    //   this.posts = userInfo.userAccount.post.dept.id;
    }else {
      this.posts = null;
    }

  }

  ngOnInit() {
    this.getQueryHead();
    this.getTablesData();
  }

  ngAfterViewInit() {
    this.loadStates.emit(true);
  }

  onEvent() {
    this.rowData = [];
    this.getQueryHead();
    this.getTablesData();
  }
//  注销按钮
//   loadTwo(){
//     this.userAuthService.removeUserInfo();
//     this.router.navigateByUrl('/passport');
//   }

  open(data: any): void {
    this.visible = true;
    this.detailsData = data;

    // 触发调用子组件接口
    this.child.getIcon(this.detailsData['JJCDH'], this.detailsData['CPHM'], this.detailsData['MDID']);
    this.child.getTablesData(this.detailsData['JJCDH'], this.detailsData['CPHM'], this.detailsData['MDID']);
    for(let i=0; i < this.reportList.length ; i++){
      this.child.getHead(this.reportList[i].headApi,
                          this.detailsData['JJCDH'],
                          this.detailsData['CPHM'],
                          this.detailsData['MDID']);
    }
  }

  close(): void {
    this.visible = false;
    this.child.visible = 'none';
    this.child.rowData = [];
    this.child.total = '';
  }

  getTablesData() {
    this.isRefresh = true;
    let data = {
      'interfaceMethod': 'ipmCLZKForAppService.getLeftTotal', 'pdata': {
        "KEY": this.query, 'MDID': this.posts
      }
    };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            let nowDate = new Date().getTime();
            for (let i = 0, len = data.length; i < len; i++) {
              data[i]['JCRQ_SJ'] = this.timesMDHMS(data[i]['JCRQ_SJ']);
              data[i]['FWLXMC'] = this.getSlicpt(data[i]['FWLXMC']);
              if (data[i]['YJJCRQ_SJ'] !== undefined) {
                data[i]['YJJCSJ'] = parseInt(((nowDate - new Date(data[i]['YJJCRQ_SJ']).getTime()) / 1000 / 60).toFixed());
              }
            }
            data = data.sort(this.sortarr("YJJCSJ"));
            this.rowData = data;
            if (this.rowData.length === 0) {
              this.msg.info(`未找到满足条件的数据`);
            }
            this.isRefresh = false;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取 查询头部
  getQueryHead() {
    let data = {'interfaceMethod': 'ipmCLZKForAppService.getClzkHead', 'pdata': { 'MDID': this.posts }};
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.queryList = data;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 截取 月、日、时、分、秒
  timesMDHMS(key: string) {
    if (key !== undefined) {
      key = key.slice(5, 16);
    }
    return key;
  }

  // 切割服务分类
  getSlicpt(data: string) {
    if (data !== undefined) {
      let strList = data.split(";");
      return strList;
    }
  }

  // 时间转换（0'00"）
  toHour(data) {
    let day = Math.floor(data / 1440);
    let hour = day >= 0
      ? Math.floor((data - (day * 1440)) / 60)
      : Math.floor(data / 60);
    let minute = hour >= 0
      ? Math.floor(data - (day * 1440) - (hour * 60))
      : Math.floor(data / 60 / 24);

    let time = "";
    if (day > 0) {
      // time = day + "天" + hour + "小时";
      time = day + "天" + hour + "小时";
    } else if (hour > 0) {
      time = hour + "小时" + minute + "分钟";
    } else if (minute > 0) {
      time = minute + "分钟";
    }
    return time;
  }

  showTime(data) {
    let a = data >= 0 ? '' : '-';
    data = data >= 0 ? data : -data;

    let day = Math.floor(data / 1440);
    let hour = day >= 0
      ? Math.floor((data - (day * 1440)) / 60)
      : Math.floor(data / 60);
    let minute = hour >= 0
      ? Math.floor(data - (day * 1440) - (hour * 60))
      : data < 0
        ? data
        : Math.floor(data / 60 / 24);

    let time = "";
    if (day > 0) {
      time = day + "天";
    } else if (hour) {
      time = hour + "小时";
    } else if (minute) {
      time = minute + "分钟";
    }
    return time;
  }

  // 点击查询按钮
  btnChange(key: string) {
    this.query = key;
    this.getQueryHead();
    this.getTablesData();
  }

  // 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return b[key] - a[key];
    };
  }

  reportList = [
    {
      headApi: 'ipmCLZKForAppService.getHead',
      // stepsApi: 'ipmCLZKForAppService.getDSstep',
      api: 'ipmCLZKForAppService.getDsxm',
      title: '定损报价 | 耗时：'
    },
    {
      headApi: 'ipmCLZKForAppService.queryUndoneXJDZHS',
      api: 'ipmCLZKForAppService.queryUndoneXJD',
      title: '配件询价 | 耗时：'
    },
    {
      headApi: 'ipmCLZKForAppService.queryYHZHS',
      api: 'ipmCLZKForAppService.queryYH',
      title: '配件要货 | 耗时：'
    },
    {
      headApi: 'ipmCLZKForAppService.getCLSGZHS',
      api: 'ipmCLZKForAppService.getCLSG',
      title: '车辆施工 | 耗时：'
    }
  ];

}
